'use strict';

const Controller = require('egg').Controller;

class WxController extends Controller {
  // 微信登录
  async login() {
    const { ctx, app } = this
    // 验证
    ctx.validate({
      nickname: { type: 'string', required: true, desc: '昵称' },
      avatar: { type: 'string', required: true, desc: '微信头像' },
      code: { type: 'string', required: true, desc: 'code' }
    })
    const { nickname, avatar, code } = ctx.request.body
    const wxApp = app.config.appConfig['wx']
    let list, oneList, url, wxList, token
    // 登录微信 获取 openid
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wxApp.appid + '&secret=' + wxApp.secret + '&js_code=' + code + '&grant_type=authorization_code';
    wxList = await ctx.curl(url, { dataType: 'json' })
    // console.log('------------wxList', wxList)
    let { openid, session_key } = wxList.data
    if (openid) {//成功获取 openid
      // 查询 用户是否已经存在
      oneList = await app.model.WxUser.findOne({
        where: {
          openid
        }
      })
      if (oneList) {// 已经存在
        list = await oneList.update({
          nickname, avatar, session_key
        })
      } else {// 不存在添加
        list = await app.model.WxUser.create({
          nickname, avatar, openid, session_key
        })
      }
      // 生成 token
      let ll = {
        id: list.id,
        nickname: list.nickname,
        role: list.role,
        status: list.status,
      }
      token = ctx.getToken(JSON.stringify(ll))
      list = await list.update({
        token
      })
      ctx.apiSuccess(token)
    } else {//没有获取 openid
      ctx.apiFail(wxList.data.errmsg)
    }
  }
  // 微信登录用户 信息
  async userinfo() {
    const { ctx, app } = this
    const user = ctx.wxUser
    ctx.apiSuccess(user)
    let list = await app.model.WxUser.findOne({
      where: {
        id: user.id
      },
      attributes: ['id', 'nickname', 'avatar', 'role', 'withdrawal_price', 'total_price','status']
    })
    ctx.apiSuccess(list)
  }
  
}

module.exports = WxController;

